package com.qianguo.buyer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.BaseBean;
import com.eva.androidlibrary.api.entity.Product;
import com.eva.androidlibrary.api.entity.ProductList;
import com.eva.androidlibrary.api.entity.ShopInfo;
import com.eva.androidlibrary.icon.FruitIcon;
import com.eva.androidlibrary.utils.IconfontUtil;
import com.eva.androidlibrary.widget.SimpleTagImageView;
import com.eva.androidlibrary.widget.SwipeRefreshRecyclerView;
import com.qianguo.buyer.base.BaseTitleActivity;
import com.qianguo.buyer.entity.AddShopCar;
import com.qianguo.buyer.order.BuyerOrderConfirmActivity;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.qianguo.buyer.R.id.item_buyer_product_num_text_view;

/**
 * @author eva
 * @date 16/8/16
 */
@EActivity(R.layout.activity_shop_fruit_list)
public class BuyerProductListActivity extends BaseTitleActivity {

    @ViewById(R.id.rv_fruit_list)
    SwipeRefreshRecyclerView mSwipeRefreshRecyclerView;

    @ViewById(R.id.buyer_shop_cart_total_price_text_view)
    TextView mTvShopCartPrice; // 总价

    @ViewById(R.id.buyer_shop_cart_delivery_price_text_view)
    TextView mTvDeliveryPrice; // 配送费

    @ViewById(R.id.buyer_shop_cart_layout)
    RelativeLayout mRlShopCart;

    @ViewById(R.id.buyer_shop_cart_settle_accounts_layout)
    LinearLayout mRlSettle; // 去结算

    @Extra("shop")
    ShopInfo mShopInfo;

    private List<Product> mProducts = new ArrayList<>();
    private HashMap<Product, Integer> mShopCart = new HashMap<>();
    private ProductListAdapter mAdapter;

    private int mCurPage = 1, mTotal;
    private static final int PAGE_SIZE = 20;
    private float mShopCartPrice;
    private int mShopCartId;
    private int mShopCartNum;

    public static void jumpToProductList(Context context, ShopInfo shop) {
        Intent intent = new Intent();
        intent.setClass(context, BuyerProductListActivity_.class);
        intent.putExtra("shop", shop);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return null;
    }

    @Override
    protected void initializeUI() {

        mRlSettle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuyerOrderConfirmActivity.jumpToConfirmOrder(BuyerProductListActivity.this, mShopInfo != null ? mShopInfo.getId() : "");
            }
        });
        mAdapter = new ProductListAdapter(this);
        mSwipeRefreshRecyclerView.setAdapter(mAdapter);
        mSwipeRefreshRecyclerView.setOnItemClickListener(new SwipeRefreshRecyclerView.OnRecyclerItemClickListener() {
            @Override
            public void onClick(int position) {

            }
        });

        mSwipeRefreshRecyclerView.setSwipeRefreshListener(new SwipeRefreshRecyclerView.SwipeRefreshListener() {
            @Override
            public void onLoadMore() {
                if (mProducts.size() < mTotal) {
                    getProducts(++mCurPage, PAGE_SIZE, mShopInfo.getId(), 0, 0);
                }
            }

            @Override
            public void onRefresh() {
                mCurPage = 1;
                mTotal = 0;
                mProducts.clear();
                getProducts(mCurPage, PAGE_SIZE, mShopInfo.getId(), 0, 0);
            }
        });

        if (mShopInfo != null) {
            setToolBarTitle(mShopInfo.getName());
            getProducts(mCurPage, PAGE_SIZE, mShopInfo.getId(), 0, 0);
        }
    }

    /**
     * 获取水果列表
     */
    @Background
    void getProducts(int page, int pageSize, String shopId, int categoryId, int orderType) {
        mApp.getApi().getShopFruitList(page, pageSize, shopId, categoryId, orderType, new HttpRequestCallback<ProductList>() {
            @Override
            public void onSuccess(int code, String msg, ProductList data) {
                if (mTotal == 0) {
                    mTotal = data.getTotal();
                }
                if (data.getList().size() > 0) {
                    mProducts.addAll(data.getList());
                }
                refreshUI();
            }


            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void refreshUI() {
        mSwipeRefreshRecyclerView.onCompleted();
        mSwipeRefreshRecyclerView.notifyDataSetChanged();
    }

    private class ProductListAdapter extends RecyclerView.Adapter<ProductViewHolder> {

        private Context mContext;
        private ProductListAdapter(Context context) {
            mContext = context;
        }

        @Override
        public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.item_buyer_product, null);
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
                    RecyclerView.LayoutParams.MATCH_PARENT,
                    RecyclerView.LayoutParams.WRAP_CONTENT);
            v.setLayoutParams(lp);
            return new ProductViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ProductViewHolder holder, int position) {
            holder.onBind(mProducts.get(position));
        }

        @Override
        public int getItemCount() {
            return mProducts != null ? mProducts.size() : 0;
        }
    }

    private class ProductViewHolder extends RecyclerView.ViewHolder {

        ProductViewHolder viewHolder;
        SimpleTagImageView imgCover;
        TextView tvProductName;
        TextView tvProductUnit;
        TextView tvMarketPrice;
        TextView tvProductPrice;
        Button btnBuy;
        LinearLayout numLayout;
        TextView tvAdd;
        TextView tvDelete;
        TextView tvNum;

        public ProductViewHolder(final View itemView) {
            super(itemView);
            viewHolder = this;
            imgCover = (SimpleTagImageView) itemView.findViewById(R.id.item_buyer_product_cover_image_view);
            tvProductName = (TextView) itemView.findViewById(R.id.item_buyer_product_name_text_view);
            tvProductUnit = (TextView) itemView.findViewById(R.id.item_buyer_product_unit_text_view);
            tvMarketPrice = (TextView) itemView.findViewById(R.id.item_buyer_product_market_price_text_view);
            tvProductPrice = (TextView) itemView.findViewById(R.id.item_buyer_product_price_text_view);
            btnBuy = (Button) itemView.findViewById(R.id.item_buyer_product_buy_button);
            numLayout = (LinearLayout) itemView.findViewById(R.id.item_buyer_product_num_layout);
            tvAdd = (TextView) itemView.findViewById(R.id.item_buyer_product_add_text_view);
            tvDelete = (TextView) itemView.findViewById(R.id.item_buyer_product_minus_text_view);
            tvNum = (TextView) itemView.findViewById(item_buyer_product_num_text_view);

            IconfontUtil.setIcon(BuyerProductListActivity.this, tvAdd, FruitIcon.ICON_SHOP_CART_ADD);
            IconfontUtil.setIcon(BuyerProductListActivity.this, tvDelete, FruitIcon.ICON_SHOP_CART_MINUS);
        }

        void onBind(final Product info) {
            mImageLoader.loadImage(BuyerProductListActivity.this, imgCover, info.getCover());
            tvProductName.setText(info.getName());
            tvProductUnit.setText(info.getUnit());
            tvMarketPrice.setText("￥" + Float.toString(info.getMarketPrice()));
            tvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            tvProductPrice.setText(Float.toString(info.getPrice()));
            btnBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mApp.isLogin()) {
                        addToShopCart(info, viewHolder);
                    } else {
                        BuyerLoginActivity.jumpToLogin(BuyerProductListActivity.this);
                    }
                }
            });

            tvAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addToShopCart(info, viewHolder);
                }
            });

            tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteFromShopCart(info, viewHolder);
                }
            });

        }
    }

    private int getNum(Product product) {
        return mShopCart.containsKey(product) ? mShopCart.get(product) : 0;
    }

    private void deleteFromShopCart(Product product, ProductViewHolder viewHolder) {
        int count = getNum(product) - 1;
        if (count == 0) {
            mShopCart.remove(product);
            viewHolder.btnBuy.setVisibility(View.VISIBLE);
            viewHolder.numLayout.setVisibility(View.GONE);
        } else {
            mShopCart.put(product, count);
            viewHolder.tvNum.setText(Integer.toString(count));
        }
        deleteShopCart(mApp.getUser().getToken(), mShopCartId, count, 1);

        mShopCartPrice -= product.getPrice();
        mTvShopCartPrice.setText(--mShopCartNum + "份，约￥" + mShopCartPrice);
    }

    private void addToShopCart(Product product, ProductViewHolder viewHolder) {
        if (viewHolder.btnBuy.getVisibility() == View.VISIBLE) {
            viewHolder.btnBuy.setVisibility(View.GONE);
            viewHolder.numLayout.setVisibility(View.VISIBLE);
        }

        // 显示总价
        if (mRlShopCart.getVisibility() != View.VISIBLE) {
            mRlShopCart.setVisibility(View.VISIBLE);
        }

        int count = 1;
        if (mShopCart.containsKey(product)) {
            count = mShopCart.get(product) + 1;
        }
        mShopCart.put(product, count);
        viewHolder.tvNum.setText(Integer.toString(count));

        // 本次加入购物车的商品数量是否累计, 0否, 1是, 默认否
        int leijia = count > 1 ? 1 : 0;
        addShopCart(mApp.getUser().getToken(), product.getId(), mShopInfo.getId(), leijia, 1, 1);

        mShopCartPrice += product.getPrice();
        mTvShopCartPrice.setText(++mShopCartNum + "份，约￥" + mShopCartPrice);
    }

    @Background
    void deleteShopCart(String token, int cartId, int num, int isSelected) {
        mApp.getApi().editShopCar(token, cartId, num, isSelected, new HttpRequestCallback<BaseBean>() {
            @Override
            public void onSuccess(int code, String msg, BaseBean data) {

            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    /**
     * 添加购物车
     */
    @Background
    void addShopCart(String token, String productID, String shopId, int isLeijia, int isSelected, int num) {
        mApp.getApi().addShopCar(token, productID, shopId, num, isLeijia, isSelected, new HttpRequestCallback<AddShopCar>() {
            @Override
            public void onSuccess(int code, String msg, AddShopCar data) {
                mShopCartId = data.getCartid();
                refreshUI();
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

}
